package com.gxa.educate.portal.tablet.earlyeducation.interceptor;

import com.gxa.educate.core.common.UserThreadLocal;
import com.gxa.educate.core.exception.BusinessException;
import com.gxa.educate.core.exception.ExceptionCode;
import com.gxa.educate.core.utils.RestUtils;
import com.gxa.educate.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lh
 * @date 2022/7/7 13:57
 */
@Component
public class InteceptorHandler implements HandlerInterceptor {
    private UserThreadLocal threadLocal=new UserThreadLocal();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(ExceptionCode.NULL_TOKEN_FAILED);
        }

        String url = "http://localhost:8090/checkToken";
        Map<String,Object> map=new HashMap<>();

        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.add("token",token);
        Map value = RestUtils.postWithParams(url, params);
//        //请求头（请求类型）
//        HttpHeaders httpHeaders = new HttpHeaders();
//        //指定了参数类型
//        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        //请求参数
//        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
//        params.add("token",token);
//        //请求类型
//        //HttpEntity:Spring 封装一个传递http请求的实体类型
//        HttpEntity httpEntity = new HttpEntity(params,httpHeaders);
//
//        //通过post方式发送的方法
//        Map map = restTemplate.postForObject(url,httpEntity,Map.class);
        if(!"200".equals(value.get("code"))){
            throw new BusinessException(ExceptionCode.STATIC_ERROR);
        }
        Object data = value.get("data");
        threadLocal.set(data);
        return true;
    }
}
